package cc.fs.kotlin.ui.activity.helper

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v7.app.AlertDialog

/**
 * android 6.0权限获取Activity
 * 问题：１．暂时只能申请一个权限　２．若是拒绝系统权限授予，将会下次不提示 3.便利性暂时无法判别
 * Created by fostion on 3/2/16.
 */
class RequestPermissionActivity : Activity() {
    companion object {
        var callback: RequestionPermissionCallback ? = null
        val keyPermission: String = "permission"

        fun requstPermission(activity: Activity, permission: String, _callback: RequestionPermissionCallback) {
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
                return
            }
            callback = _callback
            val intent: Intent = Intent(activity, RequestPermissionActivity::class.java)
            intent.putExtra(keyPermission, permission)
            activity.startActivity(intent)
        }
    }

    val REQUEST_PERMISSION_CODE: Int = 302
    var result: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        showTipDialog()
    }

    private fun showTipDialog() {
        AlertDialog.Builder(this@RequestPermissionActivity)
                .setTitle("权限使用申明")
                .setMessage("应用申请权限并无其他危险使用，请放心授予权限，若是拒授予权限，将会导致应用部分功能无法使用或者是异常，请多多包涵!")
                .setPositiveButton("好的", {
                    dialog, pos ->
                    val needPermission: String = intent.getStringExtra(keyPermission)
                    val isHasPermission: Int = checkSelfPermission(needPermission)
                    if (isHasPermission != PackageManager.PERMISSION_GRANTED) {
                        val permissiomArray: Array<String> = arrayOf(needPermission)
                        this@RequestPermissionActivity.requestPermissions(permissiomArray, REQUEST_PERMISSION_CODE)
                    } else {
                        result = true
                        finish()
                    }
                })
                .setNegativeButton("取消授权", {
                    dialog, pos ->
                    result = false
                    finish()
                })
                .show()
    }

    /**
     * grantResults为结果值０允许权限，１不允许权限
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.size > 0 && grantResults[0] != -1) {
                result = true
            }
            finish()
            return
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun finish() {
        callback?.onPermissionCallback(result)
        super.finish()
    }

    interface RequestionPermissionCallback {
        fun onPermissionCallback(result: Boolean)
    }
}